<?php

namespace C\S\User;

use C\L\Service;

class Invest extends Service
{
    protected function setModel()
    {
        $this->model = new \C\M\UserInvest();
    }

    public function getStatusConfig()
    {
        return [
            'status' => [
                'N' => '充值失败',
                'D' => '已忽略',
                'S' => '提交申请',
                'Y' => '充值成功',
                'C' => '已失效'
            ],
            'front_status' => [
                'S' => '审核中',
                'D' => '审核中',
                'Y' => '充值成功',
                'N' => '审核失败',
                'C' => '已失效'
            ],
            'channel' => [
                'wx'     => '微信充值',
                'alipay' => '支付宝',
                'bank'   => '银行转账'
            ],
            'reg_channel' => [
                'domain'    => '本站',
                'aiclk'     => '趣头条',
                'kuai_shou' => '快手',
                'baidu'     => '百度',
                'tencent'   => '广点通',
            ],
        ];
    }


    public function verify($id, $status)
    {
        try {
            if (!$this->di['s_user']->lock("invest:$id", 5)) {
                throw new \Exception('服务器忙,请稍后重试');
            }

            $invest = $this->search($id);
            if (!in_array($invest['status'], ['S', 'D']) || !in_array($status, ['Y', 'N', 'D', 'C'])) {
                throw new \Exception('当前订单不允许操作');
            }

            $this->di['db']->begin();

          // 更新 invest 表
            $investUpdateData = ['status' => $status, 'front_status' => $status];
            if ($status == 'Y') {
              // 计算充值次数
                $investCount = $this->getCount(
                    ['status' => 'Y', 'front_status' => 'Y', 'uid' => $invest['uid']],
                    ['status' => '=', 'front_status' => '=', 'uid' => '=']
                );
                $investUpdateData['invest_num'] = $investCount + 1;
                $investUpdateData['ok_time'] = time();
            }

            $investUpdateResult = $this->update($id, $investUpdateData);
            if (!$investUpdateResult) {
                throw new \Exception('更新失败invest');
            }

            if ($status == 'Y') {
                $stype = "invest_{$invest['channel']}";
                if (!$this->di['s_funds']->add(
                    $invest['uid'],
                    $invest['money'],
                    'money',
                    $stype,
                    $this->getChannelName($invest['channel']),
                    $id
                )) {
                    throw new \Exception('流水添加失败');
                }

                $pay = $this->di['s_config']->get('pay');
                if ($invest['channel'] == 'bank' && $pay['bank_back_status'] == 'Y') {
                    $rate = 0;

                    if ($invest['money'] >= 200000) {
                        $rate = $pay['bank_back_apr3'];
                    } elseif ($invest['money'] >= 100000 && $invest['money'] < 200000) {
                        $rate = $pay['bank_back_apr2'];
                    } elseif ($invest['money'] >= 10000 && $invest['money'] < 100000) {
                        $rate = $pay['bank_back_apr1'];
                    } elseif ($invest['money'] >= 3000 && $invest['money'] < 10000) {
                        $rate = $pay['bank_back_apr0'];
                    } else {
                        $rate = 0;
                    }

                    if ($rate > 0) {
                        $backMoney = bcmul($invest['money'], $rate / 100, 2);
                        if (!$this->di['s_funds']->add(
                            $invest['uid'],
                            $backMoney,
                            'money',
                            'bank_invest_back',
                            '银行充值返现',
                            $id
                        )) {
                            throw new \Exception('返现流水添加失败');
                        }
                    }
                }
            }

            $this->di['cache']->rPush('sms_list', json_encode([
            'uid' => $invest['uid'],
            'type' => $status == 'Y' ? 'invest_ok' : 'invest_no',
            'strArray' => [date('Y-m-d'), $invest['money']]
            ]));

            $this->di['db']->commit();
        } catch (\Exception $e) {
            if ($this->di['db']->isUnderTransaction()) {
                $this->di['db']->rollback();
            }

            $this->di['message']->setSerMsg($e->getMessage());
            return false;
        }

      // 发送用户充值消息
        switch ($status) {
            case 'Y':
                $this->sendMessage('invest_success', $invest);
                break;
            case 'N':
                $this->sendMessage('invest_failure', $invest);
                break;
            default:
                break;
        }

        return true;
    }

    private function getChannelName($channel)
    {
        switch ($channel) {
            case 'wx':
                return '微信充值';
            case 'alipay':
                return '支付宝充值';
            case 'bank':
                return '银行卡充值';
            default:
                return '其他方式充值';
        }
    }

    private function sendMessage($type, $invest)
    {
        $this->di['s_message']->sendMessageToUser(
            $invest['uid'],
            $type,
            [
            '__amount__' => $invest['money'],
            '__time__'   => date('Y-m-d H:i:s', $invest['uptime']),
            ]
        );
    }
}
